package com.buanalintas.sandals.pos.masterstock;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Bynga;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.entities.MasterUnit;
import com.buanalintas.bynga.formatter.DateFormatter;
import com.buanalintas.bynga.formatter.MoneyFormatter;
import com.buanalintas.bynga.formatter.NumberFormatter;
import com.buanalintas.bynga.generator.PageList;
import com.buanalintas.sandals.pos.entities.PosMasterItemStock;
import com.buanalintas.sandals.pos.entities.PosMasterStatus;
import com.buanalintas.sandals.pos.entities.ViewStokSandals;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

public class Stock extends Page {

//    private Field itemStockItemId;
    private Field itemStockColorId;
    private Field itemStockSizeId;
    private Field barcode;
    private Field itemStockItemId;
    private Field itemCode;
    private Field itemCode2;
    private Field itemModel;
    private Field modelName;
    private Field unitName;
    private Field itemStockUnitId;
    private Field itemStockValue;
    private Action actionShow = new Action("show", "Show stock");
    private Action actionExport = new Action("export", "Export stock");
    private static String MESSAGE_UNIT = "<!--MESSAGE-UNIT-->";
    private static String MESSAGE_STATUS = "<!--MESSAGE-STATUS-->";
    private static String MORE_BEGIN = "<!--MORE-BEGIN-->";
    private static String MORE_INPUT = "<!--MORE-INPUT-->";
    private static String MORE_END = "<!--MORE-END-->";
    private static String LESS_BEGIN = "<!--LESS-BEGIN-->";
    private static String LESS_INPUT = "<!--LESS-INPUT-->";
    private static String LESS_END = "<!--LESS-END-->";
    private static String SELECT_UNIT_VALUES = "<!--SELECT-UNIT-VALUES-->";
    private static String SELECT_STATUS_VALUES = "<!--SELECT-STATUS-VALUES-->";
    private static String SELECT_MORE_VALUES = "<!--SELECT-MORE-VALUES-->";
    private static String SELECT_LESS_VALUES = "<!--SELECT-LESS-VALUES-->";
    private static String RECAP_EXPORT = "RECAP-EXPORT";
    private static String RECAP_EXPORT_LINK = "<!--RECAP-EXPORT-LINK-->";
    private static String RECORD = "<!--RECORD-->";
    private static String LIST_DATA = "<!--LIST-DATA-->";
    private static String BUTTON_SEARCH = "<!--BUTTON-SEARCH-->";
    private NumberFormatter stockFormatter;

    public Stock() {
        setTheClass(PosMasterItemStock.class);

        itemStockColorId = new Field();
        itemStockColorId.setName("itemStockColorId");
        itemStockColorId.setCaption("color");
        itemStockColorId.setListProperties(" align=\"center\" width=\"8%\" nowrap");
        itemStockColorId.setInputProperties(" ");
        itemStockColorId.setRequired(true);
//        colorName.setInputType(Field.INPUT_COMBO_BOX);
        getFields().add(itemStockColorId);

        itemStockSizeId = new Field();
        itemStockSizeId.setName("itemStockSizeId");
        itemStockSizeId.setCaption("size");
        itemStockSizeId.setListProperties(" align=\"center\" width=\"7%\" nowrap");
        itemStockSizeId.setInputProperties(" ");
        itemStockSizeId.setRequired(true);
//        sizeName.setInputType(Field.INPUT_CHECK_BOX);
//        itemSizeId.setInputType(Field.INPUT_COMBO_BOX);
        getFields().add(itemStockSizeId);

        itemStockItemId = new Field();
        itemStockItemId.setName("itemStockItemId");
        itemStockItemId.setCaption("item");
        itemStockItemId.setListProperties(" align=\"center\" width=\"9%\" nowrap");
        itemStockItemId.setInputProperties(" ");
//        supplierModelCode.getSelectorColumns().add(new String[]{"supplierModelCode", " Code", "width=\"10%\""});
//        supplierModelCode.getSelectorColumns().add(new String[]{"supplierModelModelId", " Model", "width=\"20%\" nowrap"});
//        supplierModelCode.getSelectorColumns().add(new String[]{"supplierModelSupplierId", " Supplier", "width=\"70%\" nowrap"});
        itemStockItemId.setRequired(true);
        getFields().add(itemStockItemId);

//        itemCode = new Field();
//        itemCode.setName("itemCode");
//        itemCode.setCaption("code Item");
//        itemCode.setListProperties(" align=\"center\" width=\"12%\" nowrap");
//        itemCode.setInputProperties(" size=\"10\"");
//        itemCode.setRequired(true);
//        itemCode.setInputCase(Field.CASE_UPPER);
//        getFields().add(itemCode);
//
//        unitName = new Field();
//        unitName.setName("unitName");
//        unitName.setCaption("Name");
//        unitName.setListProperties(" align=\"center\" width=\"12%\" nowrap");
//        unitName.setInputProperties(" size=\"10\"");
//        unitName.setRequired(true);
//        unitName.setInputCase(Field.CASE_UPPER);
//        getFields().add(unitName);
//
//        itemModel = new Field();
//        itemModel.setName("itemModel");
//        itemModel.setCaption("model");
//        itemModel.setListProperties(" align=\"center\" width=\"8%\" nowrap");
//        itemModel.setInputProperties(" ");
//        getFields().add(itemModel);
//
//        barcode = new Field();
//        barcode.setName("barcode");
//        barcode.setCaption("barcode");
//        barcode.setListProperties(" align=\"center\" width=\"5%\" nowrap");
//        barcode.setInputProperties(" size=\"10\" style=\"text-align: right;\" readonly");
//        barcode.setInputCase(Field.CASE_UPPER);
//        getFields().add(barcode);

        itemStockValue = new Field();
        itemStockValue.setName("itemStockValue");
        itemStockValue.setCaption("stock");
        itemStockValue.setListProperties(" align=\"right\" size=\"5%\"");
        itemStockValue.setInputProperties(" ");
        getFields().add(itemStockValue);

        fillFields();

        setExportList(getClass().getResourceAsStream("MasterStockList.jasper"));
        setExport(getClass().getResourceAsStream("MasterStock.jasper"));
    }

//    @Override
//    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
////        itemStockItemId.setFormater(DateFormatter.getInstanceDate(this));
//        stockFormatter = NumberFormatter.getInstance();
//    }

    @Override
    public boolean isSearchVisible() {
        return false;
    }

    @Override
    public boolean isTitleVisible() {
        return false;
    }

    @Override
    public StringBuffer process() {
        if (getAction().equals(actionExport)) {
            try {
                updateExportParams();
                if ("2".equals(getCurrentUnit().getUnitName())) {
                    getResponse().setHeader("Content-Type", "application/vnd.ms-excel ");
                } else {
                    getResponse().setHeader("Content-Type", "application/pdf");
                }
                JRDataSource datasource = null;

                String mode = getRequest().getParameter("mode");
                String filterStatus = Utility.getParameterEmpty(getRequest(), "status");
                String filterMore = Utility.getParameterEmpty(getRequest(), "more");
                String filterLess = Utility.getParameterEmpty(getRequest(), "less");
                EntityManager em = getController().getEntityManager();
                PosMasterStatus status = null;
                try {
                    status = (PosMasterStatus) getEntityManager().createQuery("SELECT t FROM PosMasterStatus t WHERE t.statusId='" + Utility.getParameterEmpty(getRequest(), "filter") + "'").setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                    getExportParams().put("status", Utility.getParameterEmpty(getRequest(), "status") + " - " + status.getStatusId());
                } catch (Exception e) {
                    if ("*".equals(Utility.getParameterEmpty(getRequest(), "status"))) {
                        getExportParams().put("status", Dictionary.getValue(this, "All Status"));
                    } else {
                        getExportParams().put("status", Utility.getParameterEmpty(getRequest(), "filter"));
                    }
                }

                MasterUnit unit = null;
                try {
                    unit = (MasterUnit) getEntityManager().createQuery("SELECT t FROM MasterUnit t WHERE t.unitId='" + Utility.getParameterEmpty(getRequest(), "filter") + "'").setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                    getExportParams().put("unit", Utility.getParameterEmpty(getRequest(), "unit") + " - " + status.getStatusId());
                } catch (Exception e) {
                    if ("*".equals(Utility.getParameterEmpty(getRequest(), "unit"))) {
                        getExportParams().put("unit", Dictionary.getValue(this, "All Unit"));
                    } else {
                        getExportParams().put("unit", Utility.getParameterEmpty(getRequest(), "unit"));
                    }
                }

                getExportParams().put("title", Dictionary.getValue(this, "Item Stock Status") + " #" + Dictionary.getValue(this, "Status"));

                getExportParams().put("filter", Dictionary.getValue(this, "Status") + " " + Utility.getPostParameterEmpty(this, "Status"));
                if ("*".equals(Utility.getParameterEmpty(getRequest(), "status")) && "*".equals(Utility.getParameterEmpty(getRequest(), "unit"))) {
                    getController().setWhere("t.itemStockValue >= " + filterMore + " AND t.itemStockValue <= " + filterLess + "");
                } else if ("*".equals(Utility.getParameterEmpty(getRequest(), "status")) && !"*".equals(Utility.getParameterEmpty(getRequest(), "unit"))) {
                    getController().setWhere("t.itemStockUnitId=" + unit + " t.itemStockValue >= " + filterMore + " AND t.itemStockValue <= " + filterLess );
                } else if (!"*".equals(Utility.getParameterEmpty(getRequest(), "status")) && "*".equals(Utility.getParameterEmpty(getRequest(), "unit"))) {
                    getController().setWhere("t.statusId=" + status + " t.itemStockValue >= " + filterMore + " AND t.itemStockValue <= " + filterLess + "");
                } else {
                    getController().setWhere("t.statusId=" + status + " AND t.itemStockUnitId=" + unit + " t.itemStockValue >= " + filterMore + " AND t.itemStockValue <= " + filterLess + "");
                }
                getController().setPaginationFilter("&mode=" + mode + "&status=" + filterStatus);


                datasource = new JRBeanArrayDataSource(getController().getData(true).toArray());
                JasperPrint jasperPrint = JasperFillManager.fillReport(getClass().getResourceAsStream("Stock.jasper"), getExportParams(), datasource);
                if ("2".equals(getCurrentUnit().getUnitName())) {
                    JRXlsExporter excelExporter = new JRXlsExporter();
                    excelExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
                    excelExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, getResponse().getOutputStream());
                    excelExporter.exportReport();
                } else {
                    JasperExportManager.exportReportToPdfStream(jasperPrint, getResponse().getOutputStream());
                }
                return null;

            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            return new StringBuffer();

        } else {
            StringBuffer content = Utility.load(Bynga.BYNGA_PACKAGE_THEME + "content.html");
            Template template = new Template();
            template.loadTemplate(getClass().getResourceAsStream("/com/buanalintas/sandals/pos/masterstock/stock.html"));

            template.addValue(MESSAGE_UNIT, Dictionary.getValue(this, "Please select unit"));
            template.addValue(MESSAGE_STATUS, Dictionary.getValue(this, "Please select status"));

            EntityManager em = getEntityManager();

            StringBuffer selectMore = new StringBuffer();
            String moreValue = Utility.getPostParameterEmpty(this, "more");
            selectMore.append(moreValue);
            template.addValue(SELECT_MORE_VALUES, ""+ selectMore);
            System.out.println("more :" + selectMore);

            StringBuffer selectLess = new StringBuffer();
            String lessValue = Utility.getPostParameterEmpty(this, "less");
            selectLess.append(lessValue);
            template.addValue(SELECT_LESS_VALUES, ""+ selectLess);
            System.out.println("less :" + selectLess);

            StringBuffer selectUnit = new StringBuffer();
            Query query = em.createQuery("SELECT t FROM MasterUnit t ORDER BY t.unitName");
            String unitValue = Utility.getPostParameterEmpty(this, "unit");
            for (Object object : query.getResultList()) {
                MasterUnit unit = (MasterUnit) object;
                selectUnit.append("<option value=\"" + unit.getUnitId() + "\"" + (unitValue.equals("" + unit.getUnitId()) ? " selected" : "") + ">" + unit.getUnitName() + "</option>");
            }
            template.addValue(SELECT_UNIT_VALUES, "" + selectUnit);

            StringBuffer selectStatus = new StringBuffer();
            String statusValue = Utility.getPostParameterEmpty(this, "status");
            query = em.createQuery("SELECT t FROM PosMasterStatus t ORDER BY t.statusName");
            for (Object object : query.getResultList()) {
                PosMasterStatus status = (PosMasterStatus) object;
                selectStatus.append("<option value=\"" + status.getStatusId() + "\"" + (statusValue.equals("" + status.getStatusId()) ? " selected" : "") + ">" + status.getStatusName() + "</option>");
            }
            template.addValue(SELECT_STATUS_VALUES, "" + selectStatus);

            if (!"".equals(unitValue) && !"".equals(statusValue) && !"".equals(moreValue) && !"".equals(lessValue)) {
                StringBuffer recapExportLink = template.getEmptyElement(RECAP_EXPORT);
                Utility.replaceAll(recapExportLink, RECAP_EXPORT_LINK, "?m=" + getMenu().getMenuName() + "&a=" + actionExport.getName() + "&unit=" + unitValue + "&status=" + statusValue);
                template.addElement(RECAP_EXPORT, recapExportLink);
                getController().setCondition("t.itemStockUnitId.unitId=" + unitValue + " AND t.itemStockStatusId.statusId=" + statusValue + " AND t.itemStockValue >= " + selectMore + " AND t.itemStockValue <= " + selectLess + "");
//                template.addValue(RECORD, stockFormatter.format(getController().getCount()));
                template.addValue(LIST_DATA, PageList.process(this).toString());
            } else if (!"".equals(unitValue) && !"".equals(statusValue) && "".equals(moreValue) && "".equals(lessValue)) {
                StringBuffer recapExportLink = template.getEmptyElement(RECAP_EXPORT);
                Utility.replaceAll(recapExportLink, RECAP_EXPORT_LINK, "?m=" + getMenu().getMenuName() + "&a=" + actionExport.getName() + "&unit=" + unitValue + "&status=" + statusValue);
                template.addElement(RECAP_EXPORT, recapExportLink);
                getController().setCondition("t.itemStockUnitId.unitId=" + unitValue + " AND t.itemStockStatusId.statusId=" + statusValue );
//                template.addValue(RECORD, stockFormatter.format(getController().getCount()));
                template.addValue(LIST_DATA, PageList.process(this).toString());
            } else if (!"".equals(unitValue) && !"".equals(statusValue) && !"".equals(moreValue) && "".equals(lessValue)) {
                StringBuffer recapExportLink = template.getEmptyElement(RECAP_EXPORT);
                Utility.replaceAll(recapExportLink, RECAP_EXPORT_LINK, "?m=" + getMenu().getMenuName() + "&a=" + actionExport.getName() + "&unit=" + unitValue + "&status=" + statusValue);
                template.addElement(RECAP_EXPORT, recapExportLink);
                getController().setCondition("t.itemStockUnitId.unitId=" + unitValue + " AND t.itemStockStatusId.statusId=" + statusValue +" AND t.itemStockValue >= " + selectMore );
//                template.addValue(RECORD, stockFormatter.format(getController().getCount()));
                template.addValue(LIST_DATA, PageList.process(this).toString());
            } else if (!"".equals(unitValue) && !"".equals(statusValue) && "".equals(moreValue) && !"".equals(lessValue)) {
                StringBuffer recapExportLink = template.getEmptyElement(RECAP_EXPORT);
                Utility.replaceAll(recapExportLink, RECAP_EXPORT_LINK, "?m=" + getMenu().getMenuName() + "&a=" + actionExport.getName() + "&unit=" + unitValue + "&status=" + statusValue);
                template.addElement(RECAP_EXPORT, recapExportLink);
                getController().setCondition("t.itemStockUnitId.unitId=" + unitValue + " AND t.itemStockStatusId.statusId=" + statusValue +" AND t.itemStockValue <= " + lessValue );
//                template.addValue(RECORD, stockFormatter.format(getController().getCount()));
                template.addValue(LIST_DATA, PageList.process(this).toString());
            }else{
                template.addElement(RECAP_EXPORT, null);
            }

            template.addValue(BUTTON_SEARCH, Dictionary.getValue(this, "Search"));
            template.addValue(RECORD, null);

            Utility.replaceAll(content, Template.CONTENT_CONTENT, template.process().toString());
            updateContent(content, getMenu(), true);
            return content;
        }
    }
    
    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Master Stock"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
